//
//  NewMyMessageTableViewCell.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 16/10/14.
//  Copyright © 2016年 陈区. All rights reserved.
//

//#import "MessageDataBaseModel.h"
#import "NewMyMessageTableViewCell.h"
#import "MessageRequestModel.h"
#if __has_include(<Commom/SEGCommonConfig.h>)
#import <Commom/SEGCommonConfig.h>
#else
#import "SEGCommonConfig.h"
#endif

@implementation NewMyMessageTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    self.backgroundColor = kColor_W;
    [self setUpSubviews];
    
    return self;
}

- (void)setUpSubviews
{
    // 图片
    self.picImageView = [[UIImageView alloc] init];
    self.picImageView.backgroundColor = kColor_W;
    [self addSubview:self.picImageView];
    [self.picImageView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.mas_left).with.offset(15);
        make.centerY.equalTo(self.mas_centerY);
        make.width.mas_equalTo(44);
        make.height.mas_equalTo(44);
    }];
    [self.picImageView seg_configWithRadius:3.f];
    //未读消息数
    self.numberLabel = [[UILabel alloc] init];
    self.numberLabel.textColor = [UIColor whiteColor];
    self.numberLabel.font = [UIFont systemFontOfSize:13];
    self.numberLabel.layer.cornerRadius = 9;
    self.numberLabel.textAlignment = NSTextAlignmentCenter;
    self.numberLabel.backgroundColor = kColor_S1;
    
    self.numberLabel.layer.masksToBounds = YES;
    [self addSubview:self.numberLabel];
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.picImageView.mas_right).with.offset(2.5);
        make.top.equalTo(self.picImageView.mas_top).offset(-2.5);
        make.width.mas_equalTo(18);
        make.height.mas_equalTo(18);
    }];
    
    //时间
    self.timeLabel = [[UILabel alloc] init];
    self.timeLabel.backgroundColor = kColor_W;
    self.timeLabel.textColor = kColor_3;
    self.timeLabel.font = [UIFont systemFontOfSize:13];
    self.timeLabel.textAlignment = NSTextAlignmentRight;
    [self addSubview:self.timeLabel];

    // 名称
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.backgroundColor = kColor_W;
    self.nameLabel.layer.masksToBounds = YES;
    self.nameLabel.textColor = kColor_1;
    self.nameLabel.font = [UIFont systemFontOfSize:16];
    [self addSubview:self.nameLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.mas_right).with.offset(-15).priorityHigh();
        make.centerY.equalTo(self.nameLabel);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.picImageView.mas_right).with.offset(10);
        make.right.equalTo(self.timeLabel.mas_left).with.offset(-5);
        make.bottom.equalTo(self.picImageView.mas_centerY).with.offset(-2);
    }];
    
    [self.timeLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [self.nameLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
  
    //内容
    self.contentLabel = [[UILabel alloc] init];
    self.contentLabel.backgroundColor = kColor_W;
    self.contentLabel.layer.masksToBounds = YES;
    self.contentLabel.textColor = kColor_3;
    self.contentLabel.font = [UIFont systemFontOfSize:13];
    [self addSubview:self.contentLabel];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.picImageView.mas_right).with.offset(10);
        make.right.equalTo(self.mas_right).with.offset(-15);
        make.top.equalTo(self.picImageView.mas_centerY).with.offset(4);
    }];
    
    //分割线
    self.line = [[UIView alloc] init];
    self.line.backgroundColor = kColor_L2;
    [self addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self);
        make.right.equalTo(self);
        make.height.mas_equalTo(0.5);
        make.bottom.equalTo(self.mas_bottom);
    }];
}

- (void)showWithModel:(MessageModel*)msgModel unReadNumber:(NSString*)number
{
    [self seg_showDateWithTimeStr:msgModel.createTime];
    
    [self seg_setPicAndNameWithModel:msgModel];
    [self seg_setNumberLabelWithNumber:number];
    
    if ([msgModel.groupid hasPrefix:kMessageGroupSystemPre] || [msgModel.groupid hasPrefix:kMessageGroupServicePre]) { //系统消息 物业服务号
        self.contentLabel.text = msgModel.title;
    }
    else if ([msgModel.groupid hasPrefix:kMessageGroupLikePre]) { //点赞
        self.contentLabel.text = [NSString stringWithFormat:@"%@%@",msgModel.sender, msgModel.message];
    }else if ([msgModel.groupid hasPrefix:kMessageGroupCommentPre]){ //回复
        self.contentLabel.text = [NSString stringWithFormat:@"%@回复我：%@",msgModel.sender, msgModel.message];
    }
    else {
        if ([msgModel.contenttype isEqualToString:@"2"]) {
            self.contentLabel.text = @"[图片]";
        }
        else {
            if(!msgModel.message || msgModel.message.length == 0) {
                return;
            }
            
            //到家服务
            if ([msgModel.type isEqualToString:kMessageTypeHomeService]) {
                //防止时间过长导致主线程卡住或崩溃,解决点击推送崩溃问题
//                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//                    //过滤到家服务订单中的特殊格式
//                    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithData:[msgModel.message dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
//                    [attributedString addAttribute:NSFontAttributeName
//                                             value:[UIFont systemFontOfSize:13]
//                                             range:NSMakeRange(0, [attributedString length])];
//                    [attributedString addAttribute:NSForegroundColorAttributeName
//                                             value:kColor_3
//                                             range:NSMakeRange(0, [attributedString length])];
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        self.contentLabel.attributedText = attributedString;
//                        self.contentLabel.lineBreakMode = NSLineBreakByTruncatingTail;
//                    });
//                });
                self.contentLabel.attributedText=[self fomatDataFrom:msgModel.message];
                self.contentLabel.lineBreakMode=NSLineBreakByTruncatingTail;
            }
            else {
                self.contentLabel.text = msgModel.message;
            }
        }
    }
}
-(NSMutableAttributedString*)fomatDataFrom:(NSString*)htmlStr{
    
    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont systemFontOfSize:13]
                             range:NSMakeRange(0, [attributedString length])];
    [attributedString addAttribute:NSForegroundColorAttributeName
                             value:kColor_3
                             range:NSMakeRange(0, [attributedString length])];
    
    return attributedString;
    
}
- (void)seg_showDateWithTimeStr:(NSString *)timeStr
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = kTimeFormatStringMin;
    NSString* nowDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSString *showString;
    //不是本年就返回 YYYY
    if ([[timeStr substringWithRange:NSMakeRange(0, 4)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(0, 4)]].location == NSNotFound) {
        showString = [timeStr substringWithRange:NSMakeRange(0, 10)];
    }
    else {
        //是不是今天 不是今天 ：MM:dd
        if ([[timeStr substringWithRange:NSMakeRange(5, 5)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(5, 5)]].location == NSNotFound) {
            showString =  [timeStr substringWithRange:NSMakeRange(5, 5)];
        }
        else {
            showString =  [timeStr substringWithRange:NSMakeRange(11, 5)];
        }
    }
    
    self.timeLabel.text = showString;
//    CGFloat width = [self.timeLabel.text boundingRectWithSize:CGSizeMake(0, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : self.timeLabel.font } context:nil].size.width;
//    [self.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.mas_right).with.offset(-15).priorityHigh();
//        make.centerY.equalTo(self.nameLabel);
//        make.width.mas_equalTo(width);
//    }];
}

- (void)seg_setPicAndNameWithModel:(MessageModel*)msgModel
{
    // 图片
    if ([msgModel.groupid hasPrefix:kMessageGroupLikePre]) {
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_zan")];
        self.nameLabel.text = @"赞";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupCommentPre]) {
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_huifu")];
        self.nameLabel.text = @"回复";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupSystemPre]) { //系统消息
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_xitong")];
        self.nameLabel.text = @"系统消息";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupRadioPre]) { //帮帮小助手
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_qiuzhu")];
        self.nameLabel.text = @"互助广播";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupRadioReviewPre] && [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_shenhe")]) { //帮帮审核通知
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_shenhe")];
        self.nameLabel.text = @"审核通知";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupActivity]) { //活动
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_huodong")];
        self.nameLabel.text = @"活动通知";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupTaskPre]) { // 活动任务中奖
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_task")];
        self.nameLabel.text = @"任务奖励";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupPrizePre]) { //中奖
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_zhongjiang")];
        self.nameLabel.text = @"中奖记录";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupRecommendPre]) { //精选推荐
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_tuijian")];
        self.nameLabel.text = @"精选推荐";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupMall]) { //商城
        self.picImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_mall")];
        self.nameLabel.text = @"应用通知";
    } else if ([msgModel.groupid hasPrefix:kMessageGroupServicePre]) { //服务号
        SEGServiceBaseInfoModel *infoModel = [SEGCommonConfig shared].isHideServiceMessage ? [MessageRequestModel sharedRequestModel].serviceBaseInfoModel : [SEGServicenbrbaseinfoManager sharedManager].ServicenbrBaseInfo;
        [self.picImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kClientImageRootURL, infoModel.serviceNumberLogo]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_message_wuye")] options:SDWebImageLowPriority];
        self.nameLabel.text = infoModel.serviceNumberName;
    } else {
        if ([msgModel.businesstype isEqualToString:@"1"] || [msgModel.businesstype isEqualToString:@"2"]) //私信
        {
            [self.picImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"headimg60")]];
            [self.picImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kClientImageRootURL, msgModel.usericon]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"headimg60")] options:SDWebImageLowPriority];
        } else {
            [self.picImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"AppIcon60")]];
            [self.picImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kClientImageRootURL, msgModel.usericon]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"AppIcon60")] options:SDWebImageLowPriority];
        }

        //到家服务
        if ([msgModel.type isEqualToString:kMessageTypeHomeService]) {
            self.nameLabel.text = msgModel.sender;
        } else {
            self.nameLabel.text = msgModel.title;
        }
    }
}

- (void)seg_setNumberLabelWithNumber:(NSString *)number
{
    // 未读消息数
    if ([number length] > 0 && ![number isEqualToString:@"0"]) {
        self.numberLabel.hidden = NO;
        NSInteger num = [number integerValue] > 99 ? 99 : [number integerValue];
        self.numberLabel.text = [NSString stringWithFormat:@"%ld", (long)MIN(num, 99)];
        if ([number integerValue] > 99) {
            self.numberLabel.text = @"99+";
        }
        if ([number integerValue] > 99) {
            [self.numberLabel mas_updateConstraints:^(MASConstraintMaker* make) {
                make.width.mas_equalTo(30);
            }];
        }else if (num > 9) {
            [self.numberLabel mas_updateConstraints:^(MASConstraintMaker* make) {
                make.width.mas_equalTo(24);
            }];
        }else {
            [self.numberLabel mas_updateConstraints:^(MASConstraintMaker* make) {
                make.width.mas_equalTo(18);
            }];
        }
    }
    else {
        self.numberLabel.hidden = YES;
    }
}

@end
